﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using LoginMvc.Models;
using Microsoft.AspNetCore.Authorization;
using WebReposity.Entities;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using NLog.Fluent;
using WebInterface;
using AutoMapper;
using Microsoft.EntityFrameworkCore.Diagnostics;

namespace LoginMvc.Controllers
{
    public class LoginController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IMapper _mapper;
        private readonly ILoginService _loginService;

        public LoginController(ILogger<HomeController> logger,IMapper mapper,ILoginService loginService)
        {
            _logger = logger;
            _mapper = mapper;
            _loginService = loginService;
        }

        //当从别的页面跳转过来时，returnUrl 代表登陆成功后跳转回哪个地址
        public IActionResult SignIn(string returnUrl)
        {
            
            return View(new LoginUserDto { 
                ReturnUrl=returnUrl
            });
        }


        [HttpPost]
        public async Task<IActionResult> UserSignIn(LoginUserDto user)
        {
            _logger.LogInformation("trigered");

            if (ModelState.IsValid)
            {
                var loginUserEntity = _mapper.Map<LoginUserEntity>(user);
                if (await _loginService.CheckUser(loginUserEntity))
                {
                    //登陆授权

                    // claims 基本授权信息
                    var claims = new List<Claim>() {
                        new Claim(ClaimTypes.Name,user.Account)
                    };

                    //身份Id: 由授权信息 和 授权信息类型创建
                    var claimsIdentity = new ClaimsIdentity(claims,
                        CookieAuthenticationDefaults.AuthenticationScheme);

                    //authorizention 会自动发送 token 给客户端，并生成 cookies ,默认生命周期是 session，即浏览器关闭后登陆信息丢失
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                        new ClaimsPrincipal(claimsIdentity));

                    //设置过期时间
                    //await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                    //    new ClaimsPrincipal(claimsIdentity),
                    //    new AuthenticationProperties
                    //    {
                    //        //是否持久化
                    //        IsPersistent = true,
                    //        //过期时间
                    //        ExpiresUtc = DateTimeOffset.Now.AddDays(1)
                    //    }); ;

                    return Redirect(user.ReturnUrl);
                    //if (string.IsNullOrEmpty(user.ReturnUrl))
                    //{
                    //    return RedirectToAction("/");
                    //}
                    //else
                    //{
                    //    return Redirect(user.ReturnUrl);
                    //}
                }
                else
                {
                    return RedirectToAction(nameof(SignIn));
                }

                //await _departmentService.AddDepartment(department);
            }
            return RedirectToAction(nameof(SignIn));
        }

        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync();
            return RedirectToAction(nameof(SignIn));
        }

    }
}
